<?php
declare (strict_types=1);

namespace app\middleware;

use app\model\UserDao;
use think\admin\extend\JwtExtend;
use think\exception\HttpResponseException;
use think\Request;

class AuthMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next)
    {
        //
        $token = $request->header('Authorization');
        if (empty($token)) {
            $result = ['code' => 403, 'info' => '请先登录'];
            throw new HttpResponseException(json($result));
        }
        //$ret=JwtExtend::verify($token);
        $ret = checkToken($token);
        //$code = $ret['code'] ?? '';
        //$msg = $ret['message'] ?? '';
        $uid = $ret['uid'] ?? 0;
        if (empty($uid)) {
            $result = ['code' => 403, 'info' => '登录信息无效，请重新登录'];
            throw new HttpResponseException(json($result));
        }
        //$value = cache('login:' . $uid);
        //if (empty($value)) {
        //    $result = ['code' => 403, 'info' => '登录过期，请重新登录'];
        //    throw new HttpResponseException(json($result));
        //}
        $user = UserDao::where(['token' => $token, 'id' => $uid])->find();
        if (empty($user)) {
            $result = ['code' => 403, 'info' => '登录信息无效，请重新登录'];
            throw new HttpResponseException(json($result));
        }
        $request->uid = $user->id;
        $request->user = $user;
        return $next($request);
    }
}
